import time

from fastapi import FastAPI , Request , Response ,APIRouter , Depends , HTTPException , status
from libs.svr.auth import  auth
from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)

compManager = None
def getManager() :
    global compManager
    try:
        if compManager==None:
            from libs.comps.common.component import manager
            compManager = manager
    except Exception as er:
        print(er)
    return  compManager
app = FastAPI(docs_url=None, redoc_url=None)

def checkAuthFlag (request:Request):
    res = False
    try:
        res = request!=None and request.method=="POST" and request.url.path.find("/callapi/")==0
    except Exception as er:
        print(er)
    return  res

@app.middleware("http")
async def authRequest(request:Request , call_next):
    res = {}
    try:
        checkFlag = checkAuthFlag(request)
        if checkFlag :
            res = await call_next(request)
        else:
            res = await call_next(request)


        '''
        print(request.url)
        start_time = time.time()
        # 请求前处理
        print(f"请求路径: {request.url.path}")
        response = await call_next(request)  # 继续执行下一个中间件或路由处理函数
        # 响应后处理
        duration = time.time() - start_time
        print(f"处理时间: {duration:.4f}秒")
        response.headers["X-Process-Time"] = str(duration)
        response.headers["url"] = str(request.url)
        checkFlag = checkAuthFlag(request)
        response.headers["auth"] = str(checkFlag)
        res = response
        '''
    except Exception as er :
        print(er)
    return res


@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=app.title + " - Swagger UI",
        oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js",
        swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css",
    )
@app.get("/")
async def appRoot():
    return {
        "version":"apiSev2025.01",
        "serverTime": time.time()
    }
@app.post("/login")
async def login( request : Request , aid:str  , uid:str  , sec:str ):
    res = {}
    try:
        res = auth.login(aid , uid , sec)
    except Exception as err:
        print(err)
    return res
@app.post("/callapi/{compType}/{compCode}/{action}")
async def callApi( request:Request , compType: str , compCode: str , action:str , params:dict={} , caller:dict = Depends(auth.verify_jwt_token)):
    res= {
        "status":"0",
        "request":{
            "t" : compType ,
            "c": compCode ,
            "a":action ,
            "p":params,
            "u":caller
        },
        "version":"apiSev2025.01",
        "serverTime": time.time(),
        "response":{
        },
        "errMsg":""
    }
    try:
        manager = getManager()
        comp = manager.getComp(compType , compCode)
        if comp==None:
            res['status'] = -2000
            res['errMsg'] ="compType or compCode error."
        elif action not in comp.handlers.keys():
            res['status'] = -2001
            res['errMsg'] ="action error."
        else:
            acHandler = comp.handlers[action]
            resp = acHandler(**params)
            res['response'] = resp
            res['status'] = 1
    except Exception as er:
        print("callApi error.",er)
    return res

